package com.fusionride.wellness.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author fusionride
 * @date 2022/8/25 10:57
 */
@Service
@Slf4j
@ServerEndpoint("/websocket")
public class WebSocketService {
    private Session session;

    /**
     * 存放所有的websocket连接
     */
    private static CopyOnWriteArraySet<WebSocketService> webSocketServicesSet = new CopyOnWriteArraySet<>();

    /**
     * 建立websocket连接时自动调用
     * @param session
     */
    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        webSocketServicesSet.add(this);
        System.out.println("有新的websocket连接进入，当前连接总数为" + webSocketServicesSet.size());
    }

    /**
     * 关闭websocket连接时自动调用
     */
    @OnClose
    public void onClose(){
        webSocketServicesSet.remove(this);
        System.out.println("连接断开，当前连接总数为" + webSocketServicesSet.size());
    }

    /**
     * websocket接收到消息时自动调用
     * @param message
     */
    @OnMessage
    public void onMessage(String message){
        System.out.println("this：" + message);
    }

    /**
     * 通过websocket发送消息
     */
    public void sendMessage(String message){
        for (WebSocketService webSocketService : webSocketServicesSet){
            try {
                webSocketService.session.getBasicRemote().sendText(message);
                log.info("消息推送成功：{}",message);
            } catch (IOException e) {
                System.err.println(this + "发送消息错误:" + e.getClass() + ":" + e.getMessage());
            }
        }
    }
}
